import React, {useState,useEffect,useRef} from 'react'
import { useNavigate } from 'react-router-dom'
import { NavBar, TextArea, Avatar, Button } from 'antd-mobile'
import { List, Popup } from 'antd-mobile'
import { getUser, editUserPicture, editUserExplains } from '../../api'
import './index.css'


export default function PIM() {
  const [visible1, setVisible1] = useState(false)
  const [value, setValue] = useState('')
  const [userInfo,setUserInfo] = useState({})
  // const [fileList, setFileList] = useState([])
  const inputFile = useRef()
  const navigate = useNavigate()
  useEffect(()=>{
    async function userObj(){
      const result = await getUser()
      setUserInfo({...result[0]})
    }
    userObj()
  },[])

  function upload(){
    let file= inputFile.current.files[0]
    if(file){
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = async function() {
        const base64Data = reader.result.split(',')[1];
        const data = { 
          filename: file.name, 
          data: base64Data
        };
        const result = await editUserPicture(data)
        setUserInfo({...userInfo, picture: result})
      }
    }
    
  }

  const closePopup = () =>{
    setVisible1(false)
  }

  const finish = async()=>{
    await editUserExplains({explains:value})
    setVisible1(false)
  }

  const back = () =>{
    navigate(-1)
  }
  return (
    <div>
      <NavBar className='navbar' onBack={back}>个人信息</NavBar>
      <input type="file" ref={inputFile} style={{display: 'none'}} onInput={upload} />
      <List>
        <List.Item extra={<Avatar src={userInfo.picture ? `http://120.26.44.181/back/img/${userInfo.picture}` : ''} style={{ '--size': '64px', margin:'10px 0' }} />} onClick={()=>{
          inputFile.current.click()
        }}>
          头像
        </List.Item>
        <List.Item onClick={() => {
          setVisible1(true)
          setValue(userInfo.explains)
        }}>
          个人简介
        </List.Item>
      </List>
      <Popup
        visible={visible1}
        onMaskClick={() => {
          setVisible1(false)
        }}
        onClose={() => {
          setVisible1(false)
        }}
        bodyStyle={{ height: '100vh',backgroundColor:'#f6f6f6' }}
      >
        <NavBar className='navbar' onBack={closePopup} right={<Button onClick={finish} color='primary' size='small' fill='solid'>完成</Button>}>编辑简介</NavBar>
        <TextArea
          style={{backgroundColor:'#ffffff',padding:'10px 6px', boxSizing:'border-box'}}
          rows={5}
          placeholder='请输入内容'
          value={value}
          onChange={val => {
            setValue(val)
          }}
          showCount
          maxLength={30}
        />

      </Popup>
    </div>
  )
}
